package com.jadefashion.mobile;

import com.jadefashion.health.entity.Result;

import com.jadefashion.health.resources.*;

import com.jadefashion.health.resources.MessageConstant;
import com.jadefashion.health.resources.ValidateCodeUtils;

import com.jadefashion.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("order")
public class OrderController {

    /*@Autowired
    JedisPool jedisPool;*/
    @Autowired
    RedisTemplate redisTemplate;
    @Reference
    OrderService orderService;

    @RequestMapping("sendCode.do")
    public Object sendCode(@RequestParam("telephone") String telephone){
        Result result= null;
        ValueOperations ops = redisTemplate.opsForValue();
        try {
            String code = String.valueOf(ValidateCodeUtils.generateValidateCode(6));
//            SMSUtils.sendCode(telephone,code);
            System.out.println("生成的验证码:"+code);
            ops.set(telephone,code,90, TimeUnit.SECONDS);
            result = new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }/*finally {
            ops.close();
        }*/
        return result;
    }

    @RequestMapping("findOrderInfo.do")
    public Object findOrderInfo(@RequestParam("orderId") String orderId){
        Result result= null;
        try {
            Map<String,String> map=orderService.findOrderInfo(orderId);
            result = new Result(true, MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
        return result;
    }

    @PostMapping("submitOrder.do")
    public Object submitOrder(@RequestBody Map map){
        Result result= null;
//        Jedis resource = null;
        try {
            ValueOperations ops = redisTemplate.opsForValue();
            String checkcode = (String) ops.get(map.get("telephone"));
            if(checkcode==null||checkcode.equals("")){
                result=new Result(false,"验证码超时");
            }else if(checkcode.equals((String)map.get("validateCode"))){
                Map intMap=orderService.order(map);
                result = new Result(true,"验证码正确",intMap);
            }else {
                result = new Result(false,"验证码错误");
            }

        }catch (RuntimeException re){
//            re.printStackTrace();
            result = new Result(false, re.getMessage());
        } catch (Exception e) {
            result = new Result(false,"验证码校验失败");
        }/*finally {
            resource.close();
        }*/
        return result;
    }

    @RequestMapping("validateCode.do")
    public Object validateCode(@RequestParam("telephone") String telephone,@RequestParam("code") String code){
        Result result= null;
//        Jedis resource = null;
        try {
            ValueOperations ops = redisTemplate.opsForValue();
            String checkcode = (String) ops.get("telephone");
            if(checkcode==null||checkcode.equals("")){
                result=new Result(false,"验证码超时");
            }else if(checkcode.equals(code)){
                result = new Result(true,"验证码正确");
            }else {
                result = new Result(false,"验证码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result(false, "验证码校验失败");
        }/*finally {
            resource.close();
        }*/
        return result;
    }
    @RequestMapping("url.do")
    public Object generateUrl(@RequestParam("orderNumber") String orderNumber,@RequestParam("setMealPrice") String setMealPrice) {
        Result result= null;
        // 生成付款链接
        int i=(int)(Float.parseFloat(setMealPrice)*100);
        String url=orderService.createNative(orderNumber,String.valueOf(i));
        if (StringUtils.isBlank(url)) {
            return new Result(false, "生成付款链接失败");
        }
        return new Result(true, "生成付款链接成功",url);
    }

    @RequestMapping("/queryPayStatus")
    public Result queryPayStatus(@RequestParam("orderNumber") String out_trade_no){
        Result result=null;
        while(true){
            //调用查询接口
            Map<String,String> map = orderService.queryPayStatus(out_trade_no);
            if(map==null){//出错
                return new  Result(false, "支付出错");
            }
            try {
                String s = map.get("trade_state");
                if(map.get("trade_state").equals("SUCCESS")){//如果成功
                    orderService.updateOrderStauts(out_trade_no);
                    result=new  Result(true, "支付成功");
                    break;
                }
            } catch (Exception e) {

            }
            try {
                Thread.sleep(3000);//间隔三秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @RequestMapping("state.do")
    public Object queryPayState(@RequestParam("orderNumber") String orderNumber) {
        try {
            Result result= null;
            Integer status= orderService.findOrderStatus(orderNumber);
            return new Result(true, "查询订单状态成功",status);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, "查询订单状态失败");
        }
    }
}
